package com.ruoyi.wifiauth.controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.wifiauth.service.IGuidePageAccessService;
import com.ruoyi.wifiauth.domain.GuidePageAccess;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.core.web.page.TableDataInfo;
import java.util.concurrent.TimeUnit;
import java.util.List;

/**
 * 引导页控制器
 */
@RestController
@RequestMapping("/guide")
public class GuidePageController extends BaseController {

    @Autowired
    private IGuidePageAccessService guidePageAccessService;

    @Autowired
    private RedisService redisService;

    /**
     * 保存引导页访问参数
     */
    @PostMapping("/save")
    public AjaxResult saveGuidePageAccess(@RequestBody GuidePageAccess guidePageAccess,
                                          HttpServletRequest request) {
        try {
            // 频率限制：同一IP 3秒内只能访问一次
            String clientIp = getClientIP(request);
            String limitKey = "guide:save:lim:" + clientIp;
            if (Boolean.TRUE.equals(redisService.hasKey(limitKey))) {
                return error("请求过于频繁，请稍后重试");
            }
            redisService.setCacheObject(limitKey, 1, 3L, TimeUnit.SECONDS);

            // 设置客户端信息
            guidePageAccess.setUserIp(clientIp);
            guidePageAccess.setUserAgent(request.getHeader("User-Agent"));
            guidePageAccess.setReferer(request.getHeader("Referer"));

            // 参数验证
            if (guidePageAccess.getDeviceId() == null || guidePageAccess.getDeviceId().trim().isEmpty()) {
                return error("设备ID不能为空");
            }

            // 保存记录
            int result = guidePageAccessService.saveGuidePageAccess(guidePageAccess);
            if (result > 0) {
                return success("保存成功").put("sessionId", guidePageAccess.getSessionId());
            } else {
                return error("保存失败");
            }
        } catch (Exception e) {
            logger.error("保存引导页访问记录失败", e);
            return error("系统异常，请稍后重试");
        }
    }

    /**
     * 根据会话ID查询引导页访问记录
     */
    @GetMapping("/session/{sessionId}")
    public AjaxResult getBySessionId(@PathVariable String sessionId) {
        try {
            GuidePageAccess guidePageAccess = guidePageAccessService.selectBySessionId(sessionId);
            if (guidePageAccess != null) {
                return success(guidePageAccess);
            } else {
                return error("未找到对应的访问记录");
            }
        } catch (Exception e) {
            logger.error("查询引导页访问记录失败", e);
            return error("查询失败");
        }
    }

    /**
     * 根据设备ID查询引导页访问记录列表
     */
    @GetMapping("/device/{deviceId}")
    public AjaxResult getByDeviceId(@PathVariable String deviceId) {
        try {
            List<GuidePageAccess> list = guidePageAccessService.selectByDeviceId(deviceId);
            return success(list);
        } catch (Exception e) {
            logger.error("查询设备访问记录失败", e);
            return error("查询失败");
        }
    }

    /**
     * 查询引导页访问记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(GuidePageAccess guidePageAccess) {
        startPage();
        List<GuidePageAccess> list = guidePageAccessService.selectGuidePageAccessList(guidePageAccess);
        return getDataTable(list);
    }

    /**
     * 根据ID查询引导页访问记录详情
     */
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        try {
            GuidePageAccess guidePageAccess = guidePageAccessService.selectById(id);
            if (guidePageAccess != null) {
                return success(guidePageAccess);
            } else {
                return error("未找到对应的访问记录");
            }
        } catch (Exception e) {
            logger.error("查询引导页访问记录详情失败", e);
            return error("查询失败");
        }
    }

    /**
     * 获取客户端真实IP地址
     */
    private String getClientIP(HttpServletRequest request) {
        String xip = request.getHeader("X-Real-IP");
        String xfor = request.getHeader("X-Forwarded-For");
        if (xfor != null && !xfor.isEmpty() && !"unknown".equalsIgnoreCase(xfor)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = xfor.indexOf(",");
            if (index != -1) {
                return xfor.substring(0, index);
            } else {
                return xfor;
            }
        }
        xfor = xip;
        if (xfor != null && !xfor.isEmpty() && !"unknown".equalsIgnoreCase(xfor)) {
            return xfor;
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("Proxy-Client-IP");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getRemoteAddr();
        }
        return xfor;
    }
} 